// pages/home/index.js
Page({
  data: {
    foodItems: [],
    weekRecipes: [],
    showFullRecipe: false,
    fullWeekRecipes: [],
    recipeId: '',
    loading: false,
    lastUpdateTime: ''
  },

  // 启用页面下拉刷新
  onPullDownRefresh: function() {
    console.log('下拉刷新');
    this.getLatestRecipe();
    
    // 完成刷新后停止下拉动画
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  onLoad: function() {
    // 页面加载时获取数据
    this.getFoodItems();
    this.getLatestRecipe();
  },
  
  onShow: function() {
    // 页面显示时的逻辑
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        active: 0
      });
    }
  },

  // 获取冰箱食材数据
  getFoodItems: function() {
    const db = wx.cloud.database();
    db.collection('foodItems').get({
      success: res => {
        if (res.data && res.data.length > 0) {
          // 处理食材数据，添加状态和颜色
          const processedFoodItems = res.data.map(item => ({
            ...item,
            percentage: Math.round((item.currentAmount / item.maxAmount) * 100),
            color: this.getFoodStatusColor(item.currentAmount / item.maxAmount),
            status: this.getFoodStatus(item.currentAmount / item.maxAmount),
            statusClass: this.getFoodStatusClass(item.currentAmount / item.maxAmount)
          }));
          
          this.setData({
            foodItems: processedFoodItems,
            lastUpdateTime: this.formatTime(new Date())
          });
        }
      },
      fail: err => {
        console.error('获取食材数据失败', err);
        wx.showToast({
          title: '获取食材信息失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取最新食谱
  getLatestRecipe: function() {
    this.setData({ loading: true });
    
    // 先尝试调用云函数获取最新食谱
    wx.cloud.callFunction({
      name: 'recipeManager',
      data: {
        action: 'getRecipe'
      },
      success: res => {
        this.setData({ loading: false });
        
        console.log('获取食谱返回:', res);
        if (res.result && res.result.success && res.result.data) {
          const recipeData = res.result.data;
          if (recipeData.weeklyRecipes && recipeData.weeklyRecipes.length > 0) {
            this.setData({
              weekRecipes: recipeData.weeklyRecipes.slice(0, 2),
              fullWeekRecipes: recipeData.weeklyRecipes,
              recipeId: recipeData._id,
              lastUpdateTime: this.formatTime(new Date(recipeData.createTime))
            });
            return;
          }
        }
        
        // 如果云函数未返回有效数据，则尝试从数据库直接获取
        this.getRecipeFromDB();
      },
      fail: err => {
        console.error('获取食谱失败', err);
        this.setData({ loading: false });
        
        // 失败时尝试从数据库直接获取
        this.getRecipeFromDB();
      }
    });
  },

  // 从数据库获取食谱（备用方法）
  getRecipeFromDB: function() {
    const db = wx.cloud.database();
    db.collection('recipes')
      .orderBy('createTime', 'desc')
      .limit(1)
      .get({
        success: res => {
          if (res.data && res.data.length > 0) {
            const recipeData = res.data[0];
            if (recipeData.weeklyRecipes && recipeData.weeklyRecipes.length > 0) {
              this.setData({
                weekRecipes: recipeData.weeklyRecipes.slice(0, 2),
                fullWeekRecipes: recipeData.weeklyRecipes,
                recipeId: recipeData._id,
                lastUpdateTime: this.formatTime(new Date(recipeData.createTime))
              });
            } else {
              this.setData({
                weekRecipes: this.createDefaultRecipes().slice(0, 2),
                fullWeekRecipes: this.createDefaultRecipes()
              });
            }
          } else {
            this.setData({
              weekRecipes: this.createDefaultRecipes().slice(0, 2),
              fullWeekRecipes: this.createDefaultRecipes()
            });
          }
        },
        fail: err => {
          console.error('从数据库获取食谱失败', err);
          this.setData({ 
            weekRecipes: this.createDefaultRecipes().slice(0, 2),
            fullWeekRecipes: this.createDefaultRecipes()
          });
        }
      });
  },

  // 创建默认食谱（当没有数据时显示）
  createDefaultRecipes: function() {
    const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    return weekDays.map(day => ({
      day,
      meals: [
        { type: '早餐', content: '牛奶、鸡蛋、全麦面包' },
        { type: '午餐', content: '米饭、清炒时蔬、红烧肉' },
        { type: '晚餐', content: '米饭、清蒸鱼、凉拌黄瓜' }
      ]
    }));
  },

  // 重新生成食谱
  regenerateRecipe: function() {
    wx.showModal({
      title: '提示',
      content: '确定要重新生成食谱吗？这可能需要1-2分钟时间',
      success: (res) => {
        if (res.confirm) {
          this.callGenerateRecipeFunction();
        }
      }
    });
  },

  // 调用云函数生成食谱
  callGenerateRecipeFunction: function() {
    wx.showLoading({
      title: '正在生成...',
      mask: true
    });
    
    // 开始计时
    const startTime = Date.now();
    
    wx.cloud.callFunction({
      name: 'recipeManager',
      data: {
        action: 'regenerateRecipe'
      },
      success: res => {
        // 计算耗时
        const duration = ((Date.now() - startTime) / 1000).toFixed(1);
        console.log(`食谱生成完成，耗时${duration}秒`, res);
        
        wx.hideLoading();
        
        if (res.result && res.result.success) {
          wx.showToast({
            title: `食谱已更新`,
            icon: 'success',
            duration: 2000
          });
          
          // 如果返回了食谱数据，直接更新
          if (res.result.recipe) {
            this.setData({
              weekRecipes: res.result.recipe.slice(0, 2),
              fullWeekRecipes: res.result.recipe,
              recipeId: res.result.recipeId || ''
            });
          } else {
            // 否则重新获取
            setTimeout(() => {
              this.getLatestRecipe();
            }, 1000);
          }
        } else {
          console.error('生成食谱失败', res);
          let errorMsg = res.result && res.result.message 
            ? res.result.message 
            : '生成失败，请稍后重试';
            
          wx.showModal({
            title: '生成失败',
            content: errorMsg,
            showCancel: false
          });
        }
      },
      fail: err => {
        wx.hideLoading();
        console.error('调用云函数失败', err);
        
        // 尝试从错误信息中提取更详细的错误
        let errorContent = '生成失败，请稍后重试';
        if (err.errMsg) {
          if (err.errMsg.includes('timeout')) {
            errorContent = '请求超时，请稍后再试。云函数可能正在执行，请稍等片刻后点击刷新查看结果。';
          } else if (err.errMsg.includes('-504002')) {
            errorContent = 'API密钥配置错误，请检查云函数环境变量';
          } else if (err.errMsg.includes('cannot find module')) {
            errorContent = '云函数缺少必要依赖，请重新部署云函数';
          }
        }
        
        wx.showModal({
          title: '错误',
          content: errorContent,
          showCancel: false
        });
      }
    });
  },

  // 工具函数：获取食材状态颜色
  getFoodStatusColor: function(ratio) {
    if (ratio >= 0.7) return '#00a870';
    if (ratio >= 0.3) return '#ed7b2f';
    return '#e34d59';
  },

  // 工具函数：获取食材状态文本
  getFoodStatus: function(ratio) {
    if (ratio >= 0.7) return '充足';
    if (ratio >= 0.3) return '适中';
    return '不足';
  },

  // 工具函数：获取食材状态样式类
  getFoodStatusClass: function(ratio) {
    if (ratio >= 0.7) return 'status-high';
    if (ratio >= 0.3) return 'status-medium';
    return 'status-low';
  },

  // 工具函数：格式化时间
  formatTime: function(date) {
    const hour = date.getHours();
    const minute = date.getMinutes();
    return `今天 ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  },

  // 查看完整食谱
  viewFullRecipe: function() {
    if (this.data.fullWeekRecipes.length > 0) {
      wx.navigateTo({
        url: '/pages/recipe/full/index'
      });
    } else {
      wx.showToast({
        title: '暂无完整食谱',
        icon: 'none'
      });
    }
  },

  // 测试API连接
  testApiConnection: function() {
    wx.showLoading({
      title: '测试中...',
      mask: true
    });
    
    console.log('开始测试API连接');
    
    wx.cloud.callFunction({
      name: 'recipeManager',
      data: {
        action: 'testApi'
      },
      success: res => {
        wx.hideLoading();
        console.log('API测试结果:', res);
        
        if (res.result && res.result.success) {
          wx.showModal({
            title: '测试成功',
            content: `通义千问API连接正常\n响应内容: ${res.result.response.content || '无内容'}\n模型: ${res.result.response.model || '未知'}\n请继续生成食谱`,
            showCancel: false
          });
        } else {
          // 获取详细错误信息
          let errorMsg = '未知错误';
          if (res.result) {
            errorMsg = res.result.message || '未知错误';
            if (res.result.error) {
              errorMsg += '\n\n详细信息: ' + res.result.error;
            }
          }
          
          wx.showModal({
            title: '测试失败',
            content: errorMsg,
            showCancel: false
          });
        }
      },
      fail: err => {
        wx.hideLoading();
        console.error('API测试失败:', err);
        
        // 尝试解析错误信息
        let errorContent = err.errMsg || '请求失败';
        if (err.errMsg) {
          if (err.errMsg.includes('timeout')) {
            errorContent = '请求超时，请检查网络连接和云函数配置';
          } else if (err.errMsg.includes('-504002')) {
            errorContent = 'API密钥配置错误，请检查云函数环境变量';
          } else if (err.errMsg.includes('cannot find module')) {
            errorContent = '云函数缺少必要依赖，请重新部署云函数';
          }
        }
        
        wx.showModal({
          title: '测试失败',
          content: errorContent,
          showCancel: false
        });
      }
    });
  }
}); 